package com.wbt.spring.event;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

/**
 * @author daojin
 * @date 2022/4/1 11:10 上午
 * 发布事件
 *
 * 发布事件的功能定义在ApplicationEventPublisher接口中,而ApplicationContext继承了该接口,
 * 所以最好的方法是通过实现ApplicationContextAware接口获取ApplicationContext实例,
 * 然后调用其发布事件方法。如下所示定义了一个发布容器事件的代理类
 */
@Component
public class EventPublisher implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    //发布事件
    public void publishEvent(ApplicationEvent event){
        applicationContext.publishEvent(event);
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
